<template>
  <div class="app-container">
    <el-form ref="queryFormRef" :inline="true" :model="queryParams" class="demo-form-inline"
             v-hasPermi="['develop:workorder:query']">
      <el-form-item label="工单类型" prop="type">
        <el-select v-model="queryParams.type" filterable clearable default-first-option placeholder="请选择工单类型"
                   style="width: 100%">
          <el-option v-for="item in dict.type.sys_develop_order_type"
                     :key="item.value" :label="item.label"
                     :value="item.value">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="工单来源" prop="source">
        <el-select v-model="queryParams.source" filterable clearable default-first-option placeholder="请选择工单来源"
                   style="width: 100%">
          <el-option v-for="item in dict.type.sys_order_source"
                     :key="item.value" :label="item.label"
                     :value="item.value">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="工单状态" prop="status">
        <el-select v-model="queryParams.status" size="small" clearable filterable placeholder="请选择工单状态"
                   style="width: 100%;">
          <el-option v-for="item in orderStatus" :key="item.value" :label="item.label" :value="item.value">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="负责人" prop="principalName">
        <el-input v-model="queryParams.principalName" placeholder="请填写负责人" :maxlength="20" clearable />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="searchHandler">查询</el-button>
        <el-button icon="el-icon-refresh-right" size="mini" @click="resetHandler">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="20">
      <el-col :span="12">
        <div class="grid-content bg-purple">
          <el-button plain type="primary" size="mini" icon="el-icon-plus" v-hasPermi="['develop:workorder:add']"
                     @click="openDialog(null)">增加
          </el-button>
        </div>
      </el-col>
      <el-col :span="12">
        <div class="grid-content bg-purple"></div>
      </el-col>
    </el-row>

    <el-table ref="tableRef" :data="tableData" v-loading="loading" highlight-current-row max-height="680"
              v-horizontal-scroll="'auto'" style="width: 100%;margin-top: 10px;">
      <el-table-column type="index" width="50" align="center" label="序号">
        <template slot-scope="scope">
          <span>{{ (queryParams.pageNum - 1) * queryParams.pageSize + scope.$index + 1 }}</span>
        </template>
      </el-table-column>
      <el-table-column property="type" label="工单类型" align="center" width="100"/>
      <el-table-column property="source" label="工单来源" align="center" width="100"/>
      <el-table-column property="projectName" label="项目名称" align="center" min-width="120"/>
<!--      <el-table-column property="amount" label="最高限价(元)" align="center" width="120"/>-->
      <el-table-column property="name" label="采购单位" align="center" min-width="120" />
      <el-table-column property="contactName" label="联系人" align="center" width="120"/>
      <el-table-column property="planTime" label="计划完成时间" align="center" width="150"/>
      <el-table-column property="principalName" label="负责人" align="center" width="120"/>
      <el-table-column property="synergyName" label="协同人" align="center" width="140"/>
      <el-table-column property="finishTime" label="完成时间" align="center" width="150"/>
      <el-table-column property="status" label="工单状态" align="center" width="100">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.sys_edu_order_status" :value="scope.row.status"/>
        </template>
      </el-table-column>
      <el-table-column property="schedule" label="项目状态" align="center" width="120">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.sys_project_schedule" :value="scope.row.schedule" />
        </template>
      </el-table-column>
      <el-table-column property="remark" label="备注" align="center"/>
      <el-table-column property="createBy" label="创建人" align="center" width="80"/>
      <el-table-column property="createTime" label="创建时间" align="center" sortable width="150"/>
      <el-table-column label="操作" align="center"
                       v-if="$auth.hasPermi('develop:workorder:edit') || $auth.hasPermi('develop:workorder:remove') || $auth.hasPermi('develop:workorder:view')">
        <template slot-scope="scope">
          <el-button type="text" icon="el-icon-view" v-hasPermi="['develop:workorder:view']"
                     @click="handleView(scope.row)">详情
          </el-button>
          <el-button type="text" icon="el-icon-edit" v-hasPermi="['develop:workorder:edit']"
                     @click="openDialog(scope.row)">修改
          </el-button>
          <el-popconfirm confirm-button-text="是" cancel-button-text="否" title="确定删除吗？"
                         @confirm="deleteHandler(scope.row)">
            <el-button slot="reference" icon="el-icon-delete" v-hasPermi="['develop:workorder:remove']"
                       type="text" style="margin-left: 10px">删除
            </el-button>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
                @pagination="getList"/>

    <el-dialog :title="dialogTitle === 1 ? '新增' : '修改'" :visible.sync="dialogVisible" width="700px"
               :close-on-click-modal="false" :fullscreen="device === 'mobile'">
      <el-form :model="form" :rules="rules" ref="formRef" class="demo-form">
        <el-row :gutter="20">
          <el-col :span="device === 'mobile' ? 24 : 12">
            <el-form-item label="工单类型" prop="type">
              <el-select v-model="form.type" allow-create filterable clearable default-first-option placeholder="请选择工单类型"
                         style="width: 100%">
                <el-option v-for="item in dict.type.sys_develop_order_type"
                           :key="item.value" :label="item.label"
                           :value="item.value">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="device === 'mobile' ? 24 : 12">
            <el-form-item label="项目名称" prop="projectName">
              <el-input readonly v-model="form.projectName" placeholder="请选择项目" maxlength="50">
                <el-button slot="append" icon="el-icon-search" @click="handleShowProjectSelect"></el-button>
              </el-input>
              <DeliverySelect :showFlag.sync="showFlag" @onSelected="onItemSelected"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="device === 'mobile' ? 24 : 12">
            <el-form-item label="计划完成时间" prop="planTime">
              <el-date-picker v-model="form.planTime" type="datetime" value-format="yyyy-MM-dd HH:mm:ss"
                              placeholder="请选择计划完成时间"
                              style="width: 100%">
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="device === 'mobile' ? 24 : 12">
            <el-form-item label="工单来源" prop="source">
              <el-select v-model="form.source" allow-create filterable clearable default-first-option placeholder="请选择工单来源"
                         style="width: 100%">
                <el-option v-for="item in dict.type.sys_order_source"
                           :key="item.value" :label="item.label"
                           :value="item.value">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="device === 'mobile' ? 24 : 12">
            <el-form-item label="采购单位" prop="name">
              <el-input v-model="form.name" :maxlength="50" placeholder="采购单位名称"/>
            </el-form-item>
          </el-col>
          <el-col :span="device === 'mobile' ? 24 : 12">
            <el-form-item label="联系人" prop="contactName">
              <el-input v-model="form.contactName" :maxlength="20" placeholder="联系人姓名"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="device === 'mobile' ? 24 : 12">
            <el-form-item label="负责人" prop="principalId">
              <el-select v-model="form.principalId" filterable clearable default-first-option
                         placeholder="请选择负责人"
                         style="width: 100%">
                <el-option v-for="item in userList" :key="item.userId" :label="item.userName"
                           :value="item.userId">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="device === 'mobile' ? 24 : 12">
            <el-form-item label="协同人" prop="synergyIds">
              <el-select v-model="form.synergyIds" multiple filterable clearable default-first-option
                         placeholder="请选择协同人"
                         style="width: 100%">
                <el-option v-for="item in userList" :key="item.userId" :label="item.userName"
                           :value="item.userId">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="device === 'mobile' ? 24 : 12">
            <el-form-item label="工单状态" prop="status" v-if="form.id && form.statusOld === '已完成'">
              <el-select v-model="form.status" filterable clearable default-first-option
                         placeholder="请选择工单状态"
                         style="width: 100%">
                <el-option v-for="item in dict.type.sys_edu_order_status" :key="item.value" :label="item.label"
                           :value="item.value">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
<!--          <el-col :span="device === 'mobile' ? 24 : 12" v-if="form.statusOld === '已完成' || form.statusOld === '已立项' || form.statusOld === '已立项'">-->
<!--            <el-form-item label="完成时间" prop="finishTime">-->
<!--              <el-date-picker v-model="form.finishTime" type="datetime" value-format="yyyy-MM-dd HH:mm:ss"-->
<!--                              placeholder="请选择完成时间"-->
<!--                              style="width: 100%">-->
<!--              </el-date-picker>-->
<!--            </el-form-item>-->
<!--          </el-col>-->
        </el-row>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" :maxlength="250" placeholder="请输入备注"
                    :autosize="{ minRows: 2 }"/>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm('formRef')">提交</el-button>
        <el-button @click="cancel">取消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { deleteDataApi, getDataListApi, updateDataApi, addDataApi } from "@/api/after/workorder";
import {getUserProfile, listUser} from "@/api/system/user";
import {mapGetters} from 'vuex'
import DeliverySelect from "@/components/DeliverySelect/index.vue";

export default {
  name: 'ResearchWorkOrder',
  components: {DeliverySelect},
  dicts: ['sys_develop_order_type', 'sys_order_source', 'sys_edu_order_status', 'sys_project_schedule'],
  data() {
    return {
      // 显示项目弹窗
      showFlag: false,
      // 记录上一次打开弹窗是修改or增加
      // null 增加
      // 非null 修改
      formId: null,
      // 工单状态
      orderStatus: [
        {
          value: "准备中",
          label: "准备中"
        },
        {
          value: "进行中",
          label: "进行中"
        },
        {
          value: "已完成",
          label: "已完成"
        }
      ],
      pickerOptions: {
        disabledDate(time) {
          // 禁止选择今天及今天之后的日期
          return time.getTime() > Date.now();
        }
      },
      // 加载动画
      loading: true,
      // 省份数据
      provinceList: [],
      // 弹框标题 1是增加 其他是修改
      dialogTitle: 1,
      // 弹框显示
      dialogVisible: false,
      // 新增和修改参数
      form: {
        contactName: "",
        planTime: "",
        menuType: 4,
        id: null,
        projectFundId: null, // 项目ID
        name: "", // 项目来源
        projectName: "", // 项目名称
        type: null, // 项目类型
        amount: null, // 预算金额
        source: "", // 来源（客户/代理商）
        contactPerson: "", // 联系人
        principalId: "", // 负责人ID
        synergyId: "", // 协同人ID
        synergyIds: [],
        principalName: "", // 负责人名称
        synergyName: "", // 协同人名称
        finishTime: "", // 完成时间
        level: "", // 任务单级别
        description: "", // 需求详情
        createBy: "", // 创建人
        createTime: "", // 创建时间
        remark: "", // 备注
        updateBy: "",
        updateTime: "",
        status: "准备中", // 准备中，进行中，已完成
      },
      // 表单的校验规则
      rules: {
        // projectName: [
        //   {required: true, message: "请选择项目", trigger: 'blur'}
        // ],
        type: [
          {required: true, message: "请选择工单类型", trigger: 'change'}
        ],
        amount: [
          {required: true, message: "请输入金额", trigger: 'blur'}
        ],
        source: [
          {required: true, message: "请选择工单来源", trigger: 'change'}
        ],
        name: [
          {required: true, message: "请输入采购单位名称", trigger: 'blur'}
        ],
        // contactName: [
        //   {required: true, message: "请输入联系人名称", trigger: 'blur'}
        // ],
        principalId: [
          {required: true, message: "请选择负责人", trigger: 'change'}
        ],
        planTime: [
          {required: true, message: "请选择计划完成时间", trigger: 'blur'}
        ],
        finishTime: [
          {required: true, message: "请选择完成时间", trigger: 'blur'}
        ],
      },
      // 表格数据
      tableData: [],
      // 总数条数
      total: 0,
      // 查询参数
      queryParams: {
        principalName: "",
        menuType: 4,
        technologyPerson: "",
        schemePerson: "",
        name: "",
        type: null,
        source: "",
        status: "",
        pageNum: 1,
        pageSize: 10,
      },
      // 用户信息
      user: {},
      roleGroup: {},
      postGroup: {},
      // 项目数据
      projectList: [],
      // 用户数据
      userList: []
    }
  },
  computed: {
    ...mapGetters([
      'device'
    ])
  },
  watch: {},
  created() {
    // this.provinceList = ProvinceData
    this.getList()
    this.getUserinfo()
    this.getUserList()
    // this.getAllProjectList()
  },
  activated() {
    this.getList()
  },
  methods: {
    // 查看工单详情
    handleView(row) {
      this.$router.push({ name: "ResearchOrderDetail", query: { workorderId: row.id }})
    },
    // 获取用户列表
    getUserList() {
      listUser({
        pageSize: 500,
      }).then(response => {
          this.userList = (response.rows ?? []).filter(i => !i.admin)
        }
      );
    },
    // 选中用户的回调
    onItemSelected(project) {
      console.log(project)
      this.form.industryEducationId = project.id ?? ""
      this.form.name = project.procurementUnit ?? ""
      this.form.amount = project.ceilingPrice ?? ""
      this.form.projectName = project.projectName ?? ""
      this.form.contactName = project.projectLeader ?? ""
      // this.form.type = project.type
      this.form.source = project.createBy ?? ""
      this.form.planTime = project.finishTime ?? ""
    },
    // 显示项目选择弹窗
    handleShowProjectSelect() {
      this.showFlag = true;
    },
    // 获取用户信息
    getUserinfo() {
      getUserProfile().then(response => {
        this.user = response.data;
        this.roleGroup = response.roleGroup;
        this.postGroup = response.postGroup;
      });
    },
    // 获取数据
    async getList() {
      this.loading = true
      const res = await getDataListApi(this.queryParams)
      if (res.code === 200) {
        this.tableData = res.data.list
        this.total = res.data.total
      }
      this.loading = false
    },
    // 搜索的回调
    searchHandler() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    // 删除的回调
    async deleteHandler(row) {
      const res = await deleteDataApi({
        id: row.id
      })
      if (res.code === 200) {
        this.$message({
          message: res.msg,
          type: 'success'
        });
        this.getList()
        this.dialogVisible = false
      } else {
        this.$message({
          message: res.msg,
          type: 'error'
        });
      }
    },
    // 打开弹窗
    openDialog(row) {
      if (row) {
        let synergyIds = []
        if(typeof row.synergyIds === 'string') {
          synergyIds = (row.synergyIds ?? "").split(',').filter(i => i) ?? []
        } else {
          synergyIds = (row.synergyIds ?? []).map(i => +i)
        }

        this.formId = row.id
        this.form = {
          ...row,
          synergyIds, // (row.synergyIds ?? "").split(',').filter(i => i) ?? [],
          statusOld: row.status
        }
        this.dialogTitle = 2
      } else {
        if (this.formId) {
          this.form = {...this.$options.data().form}
        }
        this.formId = null
        this.dialogTitle = 1
      }
      this.showFlag = false
      this.dialogVisible = true
      // this.resetForm('formRef')
      this.$nextTick(() => {
        this.$refs['formRef'].clearValidate();
        // this.resetForm('formRef')
      })
    },
    // 导出的回调
    // async exportHandler() {
    //   this.download('crm/newspaper/export', {
    //     ...this.queryParams,
    //     userId: this.user.userId,
    //     deptId: this.user.deptId,
    //   }, `newspaper_${new Date().getTime()}.xlsx`)
    // },
    // 表单提交
    submitForm(formName) {
      // if (this.form.isImportant === 1 && !(this.form.basis)) {
      //   this.$notify({
      //     title: '警告',
      //     message: '请选择重点依据',
      //     type: 'warning'
      //   });
      //   return false
      // }
      this.$refs[formName].validate((valid) => {
        if (valid) {
          if (this.dialogTitle === 1) {
            this.addDataHandler()
          } else {
            this.updateDataHandler()
          }
        } else {
          console.log('error submit!!');
          return false;
        }
      });
    },
    // 增加数据的回调
    async addDataHandler() {
      const payload = {
        ...this.form,
        deptId: this.user.deptId,
        userId: this.user.userId,
        createBy: this.user.nickName,
        updateBy: this.user.nickName,
      }
      const res = await addDataApi(payload)
      if (res.code === 200) {
        this.$message({
          message: res.msg,
          type: 'success'
        });
        this.getList()
        this.formId = -1
        this.dialogVisible = false
        this.$refs['formRef'].resetFields();
      } else {
        this.$message({
          message: res.msg,
          type: 'error'
        });
      }
    },
    // 修改数据的回调
    async updateDataHandler() {
      const payload = {
        ...this.form,
        updateBy: this.user.nickName,
      }
      const res = await updateDataApi(payload)
      if (res.code === 200) {
        this.$message({
          message: res.msg,
          type: 'success'
        });
        this.getList()
        this.dialogVisible = false
      } else {
        this.$message({
          message: res.msg,
          type: 'error'
        });
      }
    },
    // 重置表单
    resetForm(formName) {
      if (this.$refs[formName]) {
        this.$refs[formName].resetFields();
      }
    },
    // 重置的回调
    resetHandler() {
      this.resetForm('queryFormRef')
    },
    // 取消按钮
    cancel() {
      this.showFlag = false
      this.dialogVisible = false;
    },
  },
}
</script>

<style scoped lang="scss">
.oneLine {
  overflow: hidden;
  white-space: nowrap;
  text-overflow: ellipsis;
}

.cus_text {
  font-size: larger;
  margin: 10px;
}
</style>
